package com.liang.cloud.Util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * @author: 余亮亮
 * @description:
 * @create: 2020-01-15 15:24:59
 **/
public class CookieUtil {

    /**
     * 设置cookie
     * @param response
     * @param name
     * @param value
     * @param maxAge
     */
    public static void set(HttpServletResponse response,
                           String name,
                           String value,
                           int maxAge){
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }

    /**
     * 通过名字获取cookie
     * @param request
     * @param name
     * @return
     */
    public static Cookie get(HttpServletRequest request,
                             String name){
        HashMap<String, Cookie> cookieMap = getCookieMap(request);
        if (cookieMap.containsKey(name)){
            return cookieMap.get(name);
        }else
            return null;
    }


    /**
     * 封装cookie成hashmap<cookie的名字，cookie>
     * @param request
     * @return
     */
    public static HashMap<String,Cookie> getCookieMap(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        HashMap<String,Cookie> hashMap = new HashMap<>();
        if (cookies!=null){
            for (Cookie cookie:cookies){
                hashMap.put(cookie.getName(),cookie);
            }
        }
        return hashMap;
    }


    /**
     * 我自己思考的一种直接获取cookie
     * @param request
     * @param name
     * @return
     */
    public static Cookie getCookie(HttpServletRequest request,
                                   String name){
        Cookie[] cookies = request.getCookies();
        if (cookies!=null){
            for (Cookie cookie:cookies){
                if (cookie.getName()==name){
                    return cookie;
                }
            }
        }
        return null;
    }
}
